﻿#include "circularArray.h"
#include <QtCore/QDebug>

CircularArray::CircularArray(BroadcastDecode *analysis, uint8_t _frameHead, uint8_t _crc8Index, uint8_t _lengthIndex) :
	_analysis(analysis),
	header(0),
	tail(0),
	decodeNum(0) {
	memset(buffer, 0, 65536);
	frameHead = _frameHead;
	crc8Index = _crc8Index;
	lengthIndex = _lengthIndex;
}

CircularArray::~CircularArray(){

}

//追加数据到回环数组
void CircularArray::AddData(uint8_t *data, int length) {
	for (int i = 0; i < length; i++) {
		buffer[(uint16_t)(header + i)] = data[i];
	}
	tail += (uint16_t)length;
}

void CircularArray::AddData(QByteArray *data) {
	for (int i = 0; i < data->count(); i++) {
		buffer[(uint16_t)(tail + i)] = (uint8_t)data->at(i);
	}
	tail += (uint16_t)data->count();
}

//从回环数组中拷贝数据，必须确保指针有足够的长度
void CircularArray::CopyFromArray(uint8_t *dst, uint16_t length) {
	for (uint16_t i = 0; i < length; i++) {
		dst[i] = buffer[(uint16_t)(header + i)];
	}
}

//解析数据
void CircularArray::DecodeData() {
	decodeNum = 0;
	//剩余长度必须足够满足能取到CRC8的条件
	while (this->Length() > (crc8Index + 1)) {
		while (this->Length() > (crc8Index + 1) && buffer[header] != frameHead) {
			header++;
		}
		if (this->Length() > (crc8Index + 1)) {
			//先校验CRC8是否通过
			uint8_t *crc8Check = new uint8_t[crc8Index + 1];
			CopyFromArray(crc8Check, crc8Index + 1);
			//CRC8校验，不通过直接则跳过
			if (CRC::VerifyCrc8CheckSum(crc8Check, crc8Index + 1)) {
				uint8_t packetLength = buffer[(uint16_t)(header + lengthIndex)];
				//剩余长度必须足够取完当前包,不满足则直接结束当前循环
				if (this->Length() < packetLength) { 
					free(crc8Check);
					break;
				}	
				//填装数组
				uint8_t *decodePacket = new uint8_t[packetLength];
				CopyFromArray(decodePacket, packetLength);
				//CRC16校验
				if (CRC::VerifyCrc16CheckSum(decodePacket, packetLength)) {
					header += packetLength;
					decodeNum++;
					//处理
					_analysis->decode(decodePacket, packetLength);
				}
				else {
					header++;
				}
				free(decodePacket);
			}
			else {
				header++;
			}
			free(crc8Check);
		}
	}
}